package org.xiaojl.common;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.constants.Constants;
import org.xiaojl.sys.entity.SysResource;
import org.xiaojl.sys.entity.SysUser;
import org.xiaojl.sys.service.SysResourceService;
import org.xiaojl.sys.service.SysUserRoleService;
import org.xiaojl.sys.service.SysUserService;
import org.xiaojl.utils.ToolUtil;
import org.xiaojl.utils.WebUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

@Controller
public class LoginController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysResourceService sysResourceService;
	
	@RequestMapping(value="/loginPage")
	public String loginPage(Model model){
		log.info("进入登录页面！");
		
		model.addAttribute("message", "");
		return "login";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login(String username,String password,Model model){
		log.info("执行登录:username="+username+"，password="+password );
		String message = "";
		if (ToolUtil.isEmpty(username)) {
			message = "用户名不能为空" ;
			model.addAttribute("message", message);
			return "login";
        }
        if (ToolUtil.isEmpty(password)) {
        	message = "密码不能为空" ;
        	model.addAttribute("message", message);
        	return "login";
        }
        
        SysUser sysUser = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("loginName", username));
        if(sysUser==null){
        	model.addAttribute("message", "用户名或者密码错误");
			return "login";
        }
        if(!password.equals(sysUser.getLoginPwd())){
        	model.addAttribute("message", "用户名或者密码错误");
			return "login";
        }
        String ip = WebUtil.getIpAddress(request);
        SessionUser suser = new SessionUser();
        suser.setLoginName(username);
        suser.setRealName(sysUser.getRealName());
        suser.setSysUser(sysUser);
        suser.setIp(ip);
        WebUtil.setSessionUser(request, suser);
		return REDIRECT+"index";
	}
	
	@RequestMapping(value="/logout")
	public String logout(Model model){
		log.info("退出系统!");
		session.removeAttribute(Constants.SESSION_USER);
		model.addAttribute("message", "");
		return "login";
	}
	
	@RequestMapping(value="/index")
	public String index(Model model){
		log.info("进入系统首页");
		SessionUser user = WebUtil.getSessionUser(request);
		try {
			String tree = this.buildMenuTree(user);
			model.addAttribute("tree", tree);
		} catch (Exception e) {
			log.error("进入系统首页异常:",e);
			model.addAttribute("message", e.getMessage());
			return "login";
		}
		model.addAttribute("user", user);
		return "index";
	}
	
	/**
	 * 获取用户的菜单权限
	 */
	private String buildMenuTree(SessionUser user) throws Exception {
		// 根据用户ID得到该用户的所有角色拼成的字符串
		String roleIds = sysUserRoleService.selectRoleIdsByUserId(user.getSysUser().getId());
		if (ToolUtil.isEmpty(roleIds)) {
			log.error("==>用户[" + user.getLoginName() + "]没有配置对应的权限角色");
			throw new RuntimeException("该帐号还未分配任何系统权限");
		}
		// 根据操作员拥有的角色ID,构建管理后台的树形权限功能菜单
		return this.buildTreeByRoleIds(roleIds);
	}
	
	/**
	 * 根据操作员拥有的角色ID,构建管理后台的树形权限功能菜单
	 */
	public String buildTreeByRoleIds(String roleIds) throws Exception {
		List<SysResource> treeData = null;
		try {
			treeData = sysResourceService.selectListByRoleIds(roleIds);
			if (ToolUtil.isEmpty(treeData)) {
				throw new RuntimeException("该用户没有分配菜单权限"); // 该用户没有分配菜单权限
			}
		} catch (Exception e) {
			log.error("根据角色查询菜单出现异常！", e);
			throw new RuntimeException("根据角色查询菜单出现错误"); // 查询当前角色的
		}
		StringBuffer strJson = new StringBuffer();
		buildTreeByResource("0", strJson, treeData);
		return strJson.toString();
	}

	/**
	 * 构建管理后台的树形权限功能菜单
	 * 
	 * @param pId
	 * @param treeBuf
	 * @param menuList
	 */
	private void buildTreeByResource(String pId, StringBuffer treeBuf,List<SysResource> menuList) {
		List<SysResource> listMap = getSonMenuListByPid(pId.toString(), menuList);
		for (SysResource res : listMap) {
			String id = res.getId()+"";// id
			String name = res.getName();// 名称
			String isLeaf = res.getIsLeaf()+"";// 是否叶子
			String level = res.getLevel()+"";// 菜单层级（1、2、3、4）
			String url = res.getUrl(); // ACTION访问地址
			String navTabId = "";
			if (!ToolUtil.isEmpty(res.getTargetName())) {
				navTabId = res.getTargetName(); // 用于刷新查询页面
			}
			if ("1".equals(level)) {
				treeBuf.append("<div class='accordionHeader'>");
				treeBuf.append("<h2> <span>Folder</span> " + name + "</h2>");
				treeBuf.append("</div>");
				treeBuf.append("<div class='accordionContent'>");
			}
			//是叶子吗：0-是，1-不是
			if ("0".equals(isLeaf)) {
				treeBuf.append("<li><a href='" + url + "' target='navTab' rel='" + navTabId + "'>" + name + "</a></li>");
			} else {
				if ("1".equals(level)) {
					treeBuf.append("<ul class='tree treeFolder'>");
				} else {
					treeBuf.append("<li><a>" + name + "</a>");
					treeBuf.append("<ul>");
				}
				//递归调用
				buildTreeByResource(id, treeBuf, menuList);
				if ("1".equals(level)) {
					treeBuf.append("</ul>");
				} else {
					treeBuf.append("</ul></li>");
				}
			}
			if ("1".equals(level)) {
				treeBuf.append("</div>");
			}
		}
	}

	/**
	 * 根据(pId)获取(menuList)中的所有子菜单集合.
	 * 
	 * @param pId
	 *            父菜单ID.
	 * @param menuList
	 *            菜单集合.
	 * @return sonMenuList.
	 */
	private List<SysResource> getSonMenuListByPid(String pId,
			List<SysResource> menuList) {
		List<SysResource> sonMenuList = new ArrayList<SysResource>();
		for (SysResource menu : menuList) {
			if (menu != null) {
				String parentId = menu.getPid()+"";// 父id
				if (parentId.equals(pId)) {
					sonMenuList.add(menu);
				}
			}
		}
		return sonMenuList;
	}
}
